package pl.wroc.uni.ii.pastuszka.algorithms.evolutionary.terminators;

import java.util.Collections;
import java.util.List;

import pl.wroc.uni.ii.pastuszka.algorithms.evolutionary.Individual;

public class LackOfImprovement implements TerminationCondition {

  int maxIterWithoutImprovement;
  int itersWithoutImprovement = 0;
  float bestRank;

  public LackOfImprovement(int maxIterWithoutImprovement) {
    this.maxIterWithoutImprovement = maxIterWithoutImprovement;
  }

  @Override
  public void initialize(List<Individual> population) {
    bestRank = Collections.max(population, Individual.RANK_COMPARATOR).rank;
  }

  @Override
  public void finishIteration(List<Individual> population) {
    float currentBestRank = Collections.max(population, Individual.RANK_COMPARATOR).rank;
    if (currentBestRank > bestRank) {
      bestRank = currentBestRank;
      itersWithoutImprovement = 0;
    }
    else {
      itersWithoutImprovement++;
    }
  }

  @Override
  public boolean terminate() {
    return itersWithoutImprovement >= maxIterWithoutImprovement;
  }

}
